/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Gulp build file for the date field.
 * @author samelh@google.com (Sam El-Husseini)
 */

const gulp = require('gulp');
gulp.sourcemaps = require('gulp-sourcemaps');

const closureCompiler = require('google-closure-compiler').gulp();

/**
 * A helper method to return an closure compiler output wrapper that wraps the
 * body in a Universal Module Definition.
 * @param {string} namespace The export namespace.
 * @param {Array.<Object>} dependencies An array of dependencies to inject.
 * @return {string} The output wrapper.
 */
function outputWrapperUMD(namespace, dependencies) {
  const amdDeps = dependencies.map((d) => '\'' + d.amd + '\'' ).join(', ');
  const cjsDeps = dependencies.map((d) => `require('${d.cjs}')`).join(', ');
  const browserDeps = dependencies.map((d) => 'root.' + d.name).join(', ');
  const imports = dependencies.map((d) => d.name).join(', ');
  return `// Do not edit this file; automatically generated by gulp.

/* eslint-disable */
;(function(root, factory) {
  if (typeof define === 'function' && define.amd) { // AMD
    define([${amdDeps}], factory);
  } else if (typeof exports === 'object') { // Node.js
    module.exports = factory(${cjsDeps});
  } else { // Browser
    root.${namespace} = factory(${browserDeps});
  }
}(this, function(${imports}) {
  %output%
return ${namespace};
}));
`;
}

/**
 * Build script.
 * @return {Function} The gulp task.
 */
function build() {
  return gulp.src([
    'src/**',
    './node_modules/google-closure-library/closure/goog/**/**/*.js',
  ], {base: './'})
      .pipe(gulp.sourcemaps.init())
      .pipe(closureCompiler({
        dependency_mode: 'PRUNE',
        entry_point: './src/field_date.js',
        js_output_file: 'date_compressed.js',
        language_in: 'ECMASCRIPT_2015',
        externs: ['./externs.js'],
        output_wrapper: outputWrapperUMD('Blockly.FieldDate', [{
          name: 'Blockly',
          amd: 'blockly/core',
          cjs: 'blockly/core',
          global: 'Blockly',
        }]),
      }))
      .pipe(gulp.sourcemaps.write('.', {
        includeContent: false,
        sourceRoot: '../',
      }))
      .pipe(gulp.dest('./dist/'));
}

module.exports = {
  default: build,
  build,
};
